import { changeCount, delCart, getCartList } from '@/api/cart'
import { Toast } from 'vant'

export default {
    namespaced: true,
    state () {
        return {
            cartList: []
        }
    },
    mutations: {
        // 所以mutations的第一个参数都是state
        setCartList (state, newList) {
            state.cartList = newList
        },
        toggleChecked (state, goodsId) {
            // 让对应id项的状态取反
            const goods = state.cartList.find(item => item.goods_id === goodsId)
            goods.isChecked = !goods.isChecked
        },
        toggleAllChecked (state, flag) {
            state.cartList.forEach(item => {
                item.isChecked = flag
            })
            // console.log(flag)
        },
        changeCount (state, { goodsId, goodsNum }) {
            const goods = state.cartList.find(item => item.goods_id === goodsId)
            goods.goods_num = goodsNum
            // console.log(goods + ',' + goodsId + ',' + goodsNum)
        },
        delSelAction (state) {

        }
    },
    actions: {
        async getCartListAction (context) {
            const res = await getCartList()
            const { data } = res
            data.list.forEach(item => {
                item.isChecked = true
            })
            context.commit('setCartList', data.list)
        },
        async changeCount (context, obj) {
            // console.log(obj)
            // 先修改本地数量
            const { goodsNum, goodsId, goodsSkuId } = obj
            context.commit('changeCount', {
                goodsId,
                goodsNum
            })
            // 再更新后台数量
            await changeCount(goodsId, goodsNum, goodsSkuId)
            // console.log('修改后台数量' + goodsId + ',' + goodsNum + ',' + goodsSkuId)
        },
        async delSelAction (context) {
            const selCartList = context.getters.selCartList
            const cartIds = selCartList.map(item => item.id)
            await delCart(cartIds)
            Toast('删除成功')
            // 后台删除成功后重新拉取购物车数据
            context.dispatch('getCartListAction')
        }
    },
    getters: {
        // 求所有的商品累加总数
        cartTotal (state) {
            return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
        },
        // 选中的商品项
        selCartList (state) {
            return state.cartList.filter(item => item.isChecked)
        },
        // 选中商品的数量
        selCartNum (state, getters) {
            return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0)
        },
        // 选中商品的价格
        selCartPrice (state, getters) {
            return getters.selCartList.reduce((sum, item) => {
                return sum + item.goods_num * item.goods.goods_price_min
            }, 0)
        },
        // 是否全选
        isAllChecked (state) {
            return state.cartList.every(item => item.isChecked)
        }
    }
}